#
# chat script
#
# Copyright 2007 Helsinki Institute for Information Technology
# and the authors.
#
# Authors: Ken Rimey <rimey@hiit.fi>
#

# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

from datetime import datetime
from sys import stdin, stdout

from fusion.db.util import get_default_path
from fusion.db.db import DB, Unauthorized

default_collection = '363880bc58f194a00be83ce38a12644eebd98ef7'

class Chat(object):
    def __init__(self, path, nick, collection=default_collection):
        self.nick = nick
        self.collection = collection
        self.db = DB(path)
        self.db.import_collection(collection)
        self.mark = 0

    def loop(self):
        try:
            if not self.nick:
                self.monitor()
            elif self.guest_posting_authorized():
                self.post()
            else:
                print 'Database is not up to date.  (Is fusiond running?)'
        except KeyboardInterrupt:
            pass
        finally:
            self.db.close()

    def guest_posting_authorized(self):
        return 'post/message' in \
            self.db.list_rights(self.collection, self.collection, '')

    def post(self):
        print 'Lines typed below will be posted to the chat.  (Run this script'
        print 'in another window without the --nick option to monitor the chat.)'

        while True:
            stdout.write('> ')
            s = stdin.readline()
            if not s:
                break

            s = s.rstrip()
            if not s:
                continue

            t = datetime.utcnow().isoformat()
            key = 'message/%s/%s' % (t, self.nick)
            self.db.post(self.collection, key, s)

    def monitor(self):
        print 'Welcome lurker!  (Run this script in another window'
        print 'with the --nick option to post to the chat.)'

        while True:
            messages = self.db.query_text(self.collection, 'message',
                                          last_mark = self.mark,
                                          block = True)
            for k, v in sorted(messages):
                nick = k.split('/')[1]
                line = '%s: %s' % (nick, v)
                print line.encode('utf-8')

            self.mark = self.db.get_last_mark()

def main(**options):
    daemon = Chat(**options)
    daemon.loop()

if __name__ == '__main__':
    from optparse import OptionParser

    parser = OptionParser()

    parser.add_option('--nick', help='nickname (specify to post rather than monitor)')

    default_path = get_default_path()
    parser.add_option('--db', dest='path', default=default_path,
                      help='location of database (default is %s)' % default_path)

    options, args = parser.parse_args()
    if args:
        parser.error('incorrect number of arguments')

    main(path=options.path,
         nick=options.nick)
